// utils/markdownToWordHtml.ts
import { marked } from 'marked';

export class MarkdownToWordHtmlConverter {
  /**
   * 通过 HTML 方式生成 Word 文档（图片显示最可靠）
   */
  static async convertAndDownload(
    markdownText: string,
    filename: string = 'document.doc'
  ): Promise<void> {
    try {
      const htmlContent = await this.markdownToHtml(markdownText);
      const wordHtml = this.createWordHtml(htmlContent);
      const blob = this.htmlToBlob(wordHtml);
      this.downloadBlob(blob, filename);
    } catch (error) {
      console.error('Word 文档生成失败:', error);
      throw error;
    }
  }

  /**
   * 将 Markdown 转换为 HTML
   */
  private static async markdownToHtml(markdownText: string): Promise<string> {
    return marked.parse(markdownText);
  }

  /**
   * 创建 Word 兼容的 HTML
   */
  private static createWordHtml(htmlContent: string): string {
    return `<!DOCTYPE html>
<html xmlns:v="urn:schemas-microsoft-com:vml" 
      xmlns:o="urn:schemas-microsoft-com:office:office" 
      xmlns:w="urn:schemas-microsoft-com:office:word" 
      xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" 
      xmlns="http://www.w3.org/TR/REC-html40">
<head>
  <meta charset="UTF-8">
  <meta name="ProgId" content="Word.Document">
  <meta name="Generator" content="Microsoft Word 15">
  <meta name="Originator" content="Microsoft Word 15">
  <xml>
    <w:WordDocument>
      <w:View>Print</w:View>
      <w:Zoom>100</w:Zoom>
      <w:DoNotOptimizeForBrowser/>
      <w:ValidateAgainstSchemas/>
      <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
      <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
      <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
      <w:Compatibility>
        <w:BreakWrappedTables/>
        <w:SnapToGridInCell/>
        <w:WrapTextWithPunct/>
        <w:UseAsianBreakRules/>
        <w:DontGrowAutofit/>
        <w:SplitPgBreakAndParaMark/>
        <w:EnableOpenTypeKerning/>
        <w:DontFlipMirrorIndents/>
        <w:OverrideTableStyleHps/>
      </w:Compatibility>
    </w:WordDocument>
  </xml>
  <style>
    /* Word 兼容样式 */
    @page {
      margin: 2cm;
    }
    body {
      font-family: "Microsoft YaHei", "SimSun", Arial, sans-serif;
      font-size: 12pt;
      line-height: 1.6;
      margin: 0;
      padding: 0;
    }
    h1, h2, h3, h4, h5, h6 {
      color: #2c3e50;
      margin-top: 24pt;
      margin-bottom: 12pt;
      page-break-after: avoid;
    }
    h1 { 
      font-size: 16pt; 
      border-bottom: 2pt solid #3498db; 
      padding-bottom: 6pt; 
    }
    h2 { 
      font-size: 14pt; 
      border-left: 4pt solid #3498db; 
      padding-left: 8pt; 
    }
    h3 { font-size: 13pt; }
    h4 { font-size: 12pt; }
    
    img {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 10pt auto;
      border: 1pt solid #ddd;
      page-break-inside: avoid;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 12pt 0;
      page-break-inside: avoid;
    }
    th, td {
      border: 1pt solid #bdc3c7;
      padding: 6pt 8pt;
      text-align: left;
    }
    th {
      background: #3498db;
      color: white;
      font-weight: bold;
    }
    
    code {
      background: #f4f4f4;
      padding: 1pt 3pt;
      font-family: "Courier New", monospace;
      font-size: 11pt;
    }
    
    pre {
      background: #2c3e50;
      color: white;
      padding: 12pt;
      border-radius: 4pt;
      overflow-x: auto;
      font-family: "Courier New", monospace;
      font-size: 11pt;
      page-break-inside: avoid;
    }
    
    blockquote {
      border-left: 4pt solid #3498db;
      padding-left: 12pt;
      margin-left: 0;
      background: #f8f9fa;
      padding: 8pt;
      font-style: italic;
      color: #7f8c8d;
    }
    
    ul, ol {
      margin: 8pt 0;
      padding-left: 24pt;
    }
    
    li {
      margin: 4pt 0;
    }
    
    a {
      color: #3498db;
      text-decoration: none;
    }
    
    .page-break {
      page-break-before: always;
    }
    
    /* 图片容器样式 */
    .image-container {
      text-align: center;
      margin: 12pt 0;
      page-break-inside: avoid;
    }
    
    .image-caption {
      font-size: 10pt;
      color: #666;
      margin-top: 4pt;
      font-style: italic;
    }
  </style>
</head>
<body>
  <div class="content">
    ${this.processImagesInHtml(htmlContent)}
  </div>
</body>
</html>`;
  }

  /**
   * 处理 HTML 中的图片，确保它们能在 Word 中显示
   */
  private static processImagesInHtml(htmlContent: string): string {
    // 创建一个临时 div 来处理 HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlContent;
    
    // 处理所有图片
    const images = tempDiv.getElementsByTagName('img');
    for (let i = 0; i < images.length; i++) {
      const img = images[i];
      const altText = img.alt || '图片';
      
      // 创建图片容器
      const container = document.createElement('div');
      container.className = 'image-container';
      
      // 确保图片有正确的属性
      img.style.maxWidth = '100%';
      img.style.height = 'auto';
      
      // 添加图片说明
      const caption = document.createElement('div');
      caption.className = 'image-caption';
      caption.textContent = altText;
      
      // 重新组织结构
      container.appendChild(img.cloneNode(true));
      container.appendChild(caption);
      
      // 替换原图片
      img.parentNode?.replaceChild(container, img);
    }
    
    return tempDiv.innerHTML;
  }

  /**
   * HTML 转 Blob
   */
  private static htmlToBlob(html: string): Blob {
    // 使用 application/msword 类型确保 Word 可以打开
    return new Blob([html], { 
      type: 'application/msword' 
    });
  }

  /**
   * 下载文件
   */
  private static downloadBlob(blob: Blob, filename: string): void {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }
}